package com.ycb.controller;

import com.ycb.common.BaseContext;
import com.ycb.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * @Author ycb 上传和下载
 * @Version 1.0
 * @Date 2024/10/5 10:12
 */
@RestController
@RequestMapping("/common")
@Transactional(rollbackFor = RuntimeException.class)
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String fileLocal;

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result<String> uploadFile(MultipartFile file) throws Exception {
        //file是一个临时文件,需要转存到指定位置，否则请求完成后就会被删掉
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//后缀
        //使用UUID重新生成文件名称，防止因为文件名称相同造成文件覆盖
        String fileName = UUID.randomUUID().toString()+ suffix;
        log.info(originalFilename);
        File path = new File(fileLocal);
        if (!path.exists()) {
            path.mkdir();
        }
        Long currentUserId = BaseContext.getCurrentUserId();
        File curUserPath;
        if (currentUserId != null) {
            curUserPath = new File(path  + "\\"+ String.valueOf(currentUserId));
            if (!curUserPath.exists()) {
                curUserPath.mkdir();
            }
        } else {
            curUserPath = path;
        }
        String realName = curUserPath.getAbsolutePath() + "\\" + fileName;
        log.info("文件上传地址:{}",realName);
        try {
            file.transferTo(new File(realName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(realName);
    }

    /**
     * 文件下载
     * @param name
     * @param httpServletResponse
     */
    @GetMapping("/download")
    public void downloadFile(String name,HttpServletResponse httpServletResponse) {
        try {
            //输入流，获取服务端的文件
            File file = new File(name);
            FileInputStream fileInputStream = new FileInputStream(file);

            //输出流，将获取的文件流写到浏览器中
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("multipart/form-data");
            try {
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = fileInputStream.read(bytes))!= -1) {
                    outputStream.write(bytes,0,len);
                }
            } finally {
                //关闭资源
                outputStream.flush();
                fileInputStream.close();
                outputStream.close();;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
